// coding     :utf-8 
// @FileName  :WEBGIS/script.js
// @Time      :2024/02/14
// @Author    :Mingce Zhao

//-------------------------串口中全局变量----------------------
var x_ac;
var y_ac;
var z_ac;
var x_ang;
var y_ang;
var z_ang;
var x_mag;
var y_mag;
var z_mag;
var x_angle;
var y_angle;
var z_angle;
var x_qua;
var y_qua;
var z_qua;

//-------------串口发------------
function sendMessageToAndroid_S3() {
    var value_S3 = document.getElementById("contacts_S3").value;
    // 调用Android的方法并传递消息
    if (window.android) {
        window.android.receiveMessageFromS3(value_S3);
    } else {
        windows.print()("请稍后再试（安卓底层交互问题S3）");
    }
}

function sendMessageToAndroid_S5() {
    var value_S5 = document.getElementById("contacts_S5").value;

    return new Promise(function (resolve, reject) {
        if (window.android) {
            // 发送当前value_S5值
            window.android.receiveMessageFromS5(value_S5);
            // 定义要发送的指令数组
            var commands = "500300300025899F";
            function sendCommand() {
                let currentCommand = commands;
                window.android.receiveMessageFromS5(currentCommand);
            }
            setInterval(sendCommand, 1000);
        } else {
            console.log("请稍后再试（安卓底层交互问题S5）");
            reject("安卓底层交互问题");
        }
    });   //发送

}

function sendMessageToAndroid_S6() {
    var value_S6 = document.getElementById("contacts_S6").value;

    // 检查是否可以访问Android接口
    if (window.android) {
        // 发送当前的value_S6值
        window.android.receiveMessageFromS6(value_S6);

        // 定义第一个消息的命令字符串
        var command1 = "070400000010F1A0";
        var command2 = "080304B000018444";

        //080304B000018444读取流量   08 03 02 00 00 64 45; 08 03 02 02 37 24 F3   *0.1为真频率值

        // 发送第一个命令的函数
        function sendCommand1() {
            window.android.receiveMessageFromS6(command1);
        }

        function sendCommand2() {
            window.android.receiveMessageFromS6(command2);
        }

        // 每1000ms（1秒）发送第一个命令
        setInterval(sendCommand1, 1000);
        setInterval(sendCommand2, 1500);


    } else {
        // 如果无法访问Android接口，则提供后备选项
        window.alert("请稍后再试（安卓底层交互问题S6）");
    }
}

//---------------------- 串口收 ------------------------
// -----------------模拟数据发送---------------
function simulateDataSending() {

    // 生成0到1之间的随机数
    var random = Math.random();
    // 将随机数乘以范围，并加上起始值
    var randomDecimal = ((random * 0.000999999) + 0.000011000 + 116.281573671).toFixed(9);//纬度
    var randomDecimalx = ((random * 0.000999999) + 0.000110000 + 39.941870042).toFixed(9);//经度
    var randomDecimalh = ((random * 100) + 0 + 257.144).toFixed(9);//航向角
    var randomDecimals = ((random * 10) + 0.08).toFixed(9);//地速
    // 模拟从Android接收到的数据
    var simulatedData_S3 = "$GPYBM,SN10014311,075031.00," + randomDecimalx + "," + randomDecimal + ",40.938," + randomDecimalh + ",-13.835,0.003,0.008,-0.001," + randomDecimals + ",4429701.220,182160.558,,,1,4,22,99,,0.489,18,*53";

    // 调用处理数据的函数
    getFromAndroid_S3(simulatedData_S3);
}

// 定时发送模拟数据，每隔一段时间发送一次
setInterval(simulateDataSending, 1000); // 每隔1秒发送一次数据



var data_S3d;
function getFromAndroid_S3(data_S3) {
    var processedData_S3 = data_S3;
    document.getElementById("result_S3").innerHTML = processedData_S3;
    //<!--      document.write("Received data from Android S3:", data_S3);-->
    // Handle the received data as needed
    data_S3d = processedData_S3;
}



function getFromAndroid_S5(data_S5) {
    var processedData_S5 = data_S5;
    document.getElementById("result_S5").innerHTML = processedData_S5;
    //<!--      document.write("Received data from Android S5:", data_S5);-->
    // Handle the received data as needed
    console.log(processedData_S5);

    let newArray = processedData_S5.split("·");

    var year = newArray[0];
    var month = newArray[1];
    var day = newArray[2];
    var hour = newArray[3];
    var minute = newArray[4];
    var second = newArray[5];
    var haoSecond = newArray[6];
    var acceleration = newArray[7];
    var angularVelocity = newArray[8];
    var magneticField = newArray[9];
    var angle = newArray[10];
    var quaternion = newArray[11];

    const regex = /-?\d+\.\d+/g;
    const numbers_acceleration = acceleration.match(regex).map(Number);
    x_ac = numbers_acceleration[0];
    y_ac = numbers_acceleration[1];
    z_ac = numbers_acceleration[2];
    console.log("aaaaaaa" + x_ac);

    const numbers_angularVelocity = angularVelocity.match(regex).map(Number);
    x_ang = numbers_angularVelocity[0];
    y_ang = numbers_angularVelocity[1];
    z_ang = numbers_angularVelocity[2];

    const numbers_magneticField = magneticField.match(regex).map(Number);
    x_mag = numbers_magneticField[0];
    y_mag = numbers_magneticField[1];
    z_mag = numbers_magneticField[2];

    const numbers_angle = angle.match(regex).map(Number);
    x_angle = numbers_angle[0];
    y_angle = numbers_angle[1];
    z_angle = numbers_angle[2];

    const numbers_quaternion = quaternion.match(regex).map(Number);
    x_qua = numbers_quaternion[0];
    y_qua = numbers_quaternion[1];
    z_qua = numbers_quaternion[2];

    console.log(y_ac);
    console.log(z_ac);
    console.log(x_ang);
    console.log(y_ang);
    console.log(z_ang);
    console.log(x_mag);
    console.log(y_mag);
    console.log(z_mag);
    console.log(x_angle);
    console.log(y_angle);
    console.log(z_angle);
    console.log(x_qua);
    console.log(y_qua);
    console.log(z_qua);

    document.getElementById("result_S5x").innerHTML = newArray[0];
    document.getElementById("result_S5c").innerHTML = newArray[1];
    document.getElementById("result_S5v").innerHTML = newArray[2];
    document.getElementById("result_S5b").innerHTML = newArray[3];
    document.getElementById("result_S5n").innerHTML = newArray[4];
    document.getElementById("result_S5m").innerHTML = newArray[6];
    //document.getElementById("result_S5").innerHTML = newArray[7];
    //document.getElementById("result_S5").innerHTML = newArray[8];
    //document.getElementById("result_S5x").innerHTML = newArray[9];
    //document.getElementById("result_S5x").innerHTML = newArray[10];
    //document.getElementById("result_S5x").innerHTML = newArray[11];
    //document.getElementById("result_S5x").innerHTML = newArray[12];

}


//    function getFromAndroid_S6(data_S6) {
//      var processedData_S6 = data_S6;
//      document.getElementById("result_S6").innerHTML = processedData_S6;
//<!--      document.write("Received data from Android S6:", data_S6);-->
//      // Handle the received data as needed
//
//    }
//--------------------------------------------S6测试-----------------------
function getFromAndroid_S6(data_S6) {
    // 定义存放结果的数组
    var resultArray = [];

    // 定义需要查找的字符串
    var searchString = "070420";

    // 找到字符串的起始位置
    var startIndex = data_S6.indexOf(searchString);

    // 如果找到了字符串
    if (startIndex !== -1) {
        // 提取从起始位置开始的72个字符
        var extractedString = data_S6.substring(startIndex, startIndex + 72);

        // 将提取的字符串每两个字符分割并存入数组
        for (var i = 0; i < extractedString.length; i += 2) {
            resultArray.push(extractedString.substring(i, i + 2));
        }

        var qiufa1 = resultArray[3];
        var qiufa2 = resultArray[4];
        var aPressure1 = resultArray[5];
        var aPressure2 = resultArray[6];
        var bPressure1 = resultArray[7];
        var bPressure2 = resultArray[8];

        // 将字符串拼接
        var qiufa = qiufa1 + qiufa2;
        var aPressure = aPressure1 + aPressure2;
        var bPressure = bPressure1 + bPressure2;

        // 从16进制转换为10进制
        var qiufaDecimal = (parseInt(qiufa, 16) - 4000) / (20000 - 4000) * 100;
        var aPressureDecimal = ((parseInt(aPressure, 16) / 1000) - 4) * (1 / 4);
        var bPressureDecimal = ((parseInt(bPressure, 16) / 1000) - 4) * (1 / 4);

        console.log("球阀开度: " + qiufaDecimal + "%");
        console.log("A压力值: " + aPressureDecimal + "mpa");
        console.log("B压力值: " + bPressureDecimal + "mpa");

        document.getElementById('value_du').textContent = qiufaDecimal.toFixed(2);
        document.getElementById('value_pressure1').textContent = aPressureDecimal.toFixed(2);
        document.getElementById('value_pressure2').textContent = bPressureDecimal.toFixed(2);

        // 在页面上显示结果（可选）

        //07 10 01 90 00 01 02 0F A0 85 E8
        //07 10 01 90 00 01 02 4E 20 B4 18
        //07 10 01 90 00 01 02 27 10 9A 5C
        document.getElementById("result_S6").innerHTML = resultArray;

    } else {
        // 如果没有找到字符串，则在页面上显示错误信息
        document.getElementById("result_S6").innerHTML = "字符串 '070420' 未找到.";
    }

    // 可以根据需要处理resultArray
    // ...

    return resultArray;  // 返回结果数组
}


//------------------左侧面板收缩------------------
const toggleButton = document.getElementById('toggleButton');
toggleButton.addEventListener('click', function () {
    const leftPanel = document.querySelector('.left-panel');
    leftPanel.classList.toggle('collapsed');
    toggleButton.classList.toggle('rotated');
});

// ------------------功能列表菜单切换------------------
$(function () {
    $(".function_all").on("click", "li", function () {
        var sId = $(this).attr("id"); //获取data-id的值
        console.log(sId)
        $('#' + sId + 'Panel').removeClass('hide')
        $('#' + sId + 'Panel').siblings().addClass('hide')
    });
});

// ------------------------------------地图------------------------------------------------
var mapOptions = {
    center: [+39.943816759590774, +116.27661216853765],
    zoom: 5
}
// 在 "map" div上初始化地图
var map = L.map('map', mapOptions);

// 添加Mapbox 卫星街道作为瓦片图层
L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: '地图数据 &copy; <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'satellite-streets-v11', // 更正后的Mapbox样式 'id' 参数
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'pk.eyJ1IjoiZWdnMzY1IiwiYSI6ImNscTdvN3B3bDB0eXIya3A3NWhoYnJhd2gifQ.-JKqIgzJlA8gZ7cZ4i8u2A' // 用你的Mapbox访问令牌替换
}).addTo(map);



//----------------------------------------串口数据解析---------------------------------------------
var processedGeojsonData;//处方图数据初始化
var latitude, longitude, heading, vel_G, north_Distance, east_Distance;//纬度，经度，航向角。。。
var marker = null; // 全局初始化标记变量
var path = []; // 初始化路径数组
var pathLine; // 用于地图上显示的路径线
var isRecordingPath = false; // 路径记录开关
var isLocationEnabled = false; // 默认情况下，位置检索是关闭的
var isCurveEnabled = false; // 默认情况下，curve显示是关闭的
var curve = L.polyline([], { color: 'red' }).addTo(map);//初始化路径
var line = L.polyline([], { color: 'yellow' }).addTo(map);// 初始化线段

//-------------------------------S3收到串口处理方法-------------------------------------
function processData() {
    if (isLocationEnabled) {
        if (typeof data_S3d !== 'undefined') {
            var gpx_data = data_S3d;
            var values = gpx_data.split(",");

            console.log("ccccc" + x_ac);//--------------isLocationEnabled要开启，全局变量生效--------------------
            // ------更新全局变量，获取串口值------
            latitude = parseFloat(values[3]);
            longitude = parseFloat(values[4]);
            heading = parseFloat(values[6]);
            vel_G = parseFloat(values[11]);//地速
            north_Distance = parseFloat(values[14]);
            east_Distance = parseFloat(values[15]);

            //获取原始经纬度
            var origin = turf.point([longitude, latitude]);

            // ------更新路径数组------
            path.push([latitude, longitude]);
            console.log('Latitude:', latitude, 'Longitude:', longitude);

            // ------定位标记样式获取------
            if (marker === null) {
                // ----如果不存在，则创建标记----
                const myIcon = L.icon({
                    iconSize: [50, 50],
                    iconAnchor: [25, 25],
                    popupAnchor: [1, -34],
                    iconUrl: "../img/leaf-green.png"
                });
                marker = L.marker([latitude, longitude], { icon: myIcon, rotationOrigin: "center center" }).addTo(map);
            }
            // ----更新标记的位置和旋转角度----
            marker.setLatLng([latitude, longitude]);
            marker.setRotationAngle(heading);

            //------路径曲线------
            if (isCurveEnabled) {
                // 初始化路径Polyline，并添加到地图上
                if (curve == null) {
                    curve = new L.polyline([], { color: 'red' }).addTo(map)
                    //.bringToFront();？？？？？？？？？？？？？？？？？？？？？？？？？？将路径放在
                }
                var latlng = L.latLng(latitude, longitude);
                curve.addLatLng(latlng);
                console.log("1111", curve);
            } else {
                if (curve) {
                    console.log("R222");
                }
            }

            //应测试全局变量保存？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
            document.getElementById('saveCurveButton').addEventListener('click', function () {
                if (curve) {
                    var latlngs = curve.getLatLngs(); // 从曲线获取点
                    var data = JSON.stringify(latlngs); // 转换为 JSON
                    android.saveData(data); // 调用 Android 端的接口
                } else {
                    alert('没有可用的曲线数据来保存。');
                }
            });

            //------清除路径------
            document.getElementById('removeCurveButton').addEventListener('click', function () {
                if (curves) {
                    map.removeLayer(curves);
                    curves = null;
                }
                // 如果 curve 变量也需要清除
                if (curve) {
                    map.removeLayer(curve);
                    curve = null;
                }
            });

            // ------测试，所在点的坐标获取，判断在处方图的位置------
            //            const pointCoordinates = [longitude, latitude]; // 这里是所在点的经纬度坐标（经度，纬度）
            //            console.log(pointCoordinates);
            //            // 检查 processedGeojsonData 是否存在并且包含features
            //            if (!processedGeojsonData || !processedGeojsonData.features) {
            //                console.log("processedGeojsonData 未定义或无特征数据，跳过处理。");
            //            }else{
            //                // 判断点是否在多边形内，并输出对应的 NUMPOINTS 值
            //                processedGeojsonData.features.forEach(feature => {
            //                    const polygon = turf.polygon(feature.geometry.coordinates);
            //                    const point = turf.point(pointCoordinates);
            //
            //                    if (turf.booleanPointInPolygon(point, polygon)) {
            //                      const numPointsValue = feature.properties.NUMPOINTS;
            //                      document.getElementById("value_origin").textContent = numPointsValue;
            //                      console.log(`点在多边形内，对应的 NUMPOINTS 值为: ${numPointsValue}`);
            //                    }
            //                });
            //            }


            //------测试，喷杆位置2d模拟（俯视图）------
            //var distanceX = 0.01;  // 东西方向100米
            //var distanceY = 0.001;  // 南北方向200米

            // 获取输入框元素
            var distanceXInput = document.getElementById('distanceX');//喷杆长度
            var distanceYInput = document.getElementById('distanceY');//喷杆与机具距离
            var nozzlesInput = document.getElementById('nozzles');//喷头数
            // 获取输入框中的值
            var distanceX = parseFloat(distanceXInput.value) / 1000;
            var distanceY = parseFloat(distanceYInput.value) / 1000;
            var nozzles = parseFloat(nozzlesInput.value) - 1;//实际喷嘴数-1

            var options = { units: 'kilometers' };  // Turf需要单位，这里我们使用千米

            // 函数来平均分割线段
            function divideLineIntoSegments(start, end, segments) {
                var points = [];
                for (var i = 0; i <= segments; i++) {
                    var t = i / segments;
                    var lat = start[0] + t * (end[0] - start[0]);
                    var lng = start[1] + t * (end[1] - start[1]);
                    points.push([lat, lng]);
                }
                return points;
            }

            // 更新点和线段的函数
            var segmentPoints;
            function updatePointsAndLine(heading) {
                // 计算第一个点（东北方向）
                var point1 = turf.destination(origin, distanceY, heading, options);  // 沿着heading方向
                var point1Offset = turf.destination(point1, distanceX, heading + 90, options);  // 垂直heading方向

                // 计算第二个点（西北方向，y轴对称）
                var point2 = turf.destination(origin, distanceY, heading, options);  // 同样沿着heading方向
                var point2Offset = turf.destination(point2, distanceX, heading - 90, options);  // 垂直heading方向

                // 确定两个点的坐标
                var coordinates1 = [point1Offset.geometry.coordinates[1], point1Offset.geometry.coordinates[0]];
                var coordinates2 = [point2Offset.geometry.coordinates[1], point2Offset.geometry.coordinates[0]];
                // 更新线段坐标
                line.setLatLngs([coordinates1, coordinates2]);
                line.bringToFront();
                // 计算线段上的21个点（包括端点）
                segmentPoints = divideLineIntoSegments(coordinates1, coordinates2, nozzles);
                // 清空之前的点列表
                clearPointsList();
                // 检查每个点是否在多边形内，并输出 NUMPOINTS 值
                // 遍历每个点，检查是否在多边形内，并更新列表
                segmentPoints.forEach((point, index) => {
                    checkPointInPolygons(point, index);
                    //index正常为1，2，3.。。。。。，现在是什么？？？？？？？？？？？？？？？？？？？？？？
                });
            }

            function checkPointInPolygons(point, index) {
                // 检查 processedGeojsonData 是否存在并且包含 features
                if (!processedGeojsonData || !processedGeojsonData.features) {
                    console.log("processedGeojsonData 未定义或无特征数据，跳过处理。");
                    return;
                }
                // 判断点是否在多边形内，并输出对应的 NUMPOINTS 值
                var found = false;
                processedGeojsonData.features.forEach(feature => {
                    const polygon = turf.polygon(feature.geometry.coordinates);
                    const checkPoint = turf.point([point[1], point[0]]); // 注意：Turf 需要的坐标顺序是 [经度, 纬度]

                    if (turf.booleanPointInPolygon(checkPoint, polygon)) {
                        const numPointsValue = feature.properties.NUMPOINTS;
                        console.log(`点[${point[0]}, ${point[1]}]在多边形内，对应的 NUMPOINTS 值为: ${numPointsValue}`);
                        updatePointsList(index, numPointsValue);
                        found = true;
                    }
                });
                if (!found) {
                    numPointsValue = "null";
                    updatePointsList(index, numPointsValue);
                }
            }
            //权重值更新列表
            function updatePointsList(index, numPointsValue) {
                var pointsList = document.getElementById("pointsList");
                var listItem = pointsList.children[index] || document.createElement("li");
                listItem.textContent = `点 ${index + 1}: ${numPointsValue}`;
                if (!listItem.parentNode) {
                    pointsList.appendChild(listItem);
                }
                //在这写逻辑试试
                var value = "";
                switch (numPointsValue) {
                    case 0:
                        value = "0000";
                        break;
                    case 1:
                        value = "000A";
                        break;
                    case 2:
                        value = "0025";
                        break;
                    default:
                        value = "0000"; // 默认值
                }
                //更新对应位置的数值
                var str = "FF100020001C380001";
                for (var i = 0; i < 21; i++) {
                    if (i === index) {
                        str += value;
                    } else {
                        str += "0032";
                    }
                }
                str += "00320032003200321FFFFF";
                str += generateCRc16Modbus(str);
                window.android.receiveMessageFromS6(str);
            }

            function generateCRc16Modbus(data){
                const polynomial = 0x8005;
                let crc = 0xFFFF;

                for(let i=0;i< data.length; i++){
                    crc ^=(data.charcodeAt(i)& 0xFF);
                    for(let j=0;j<8;j++){
                        if(crc & 0x0001){
                            crc =(crc >>1)^ polynomial;
                        } else {
                            crc >>= 1;
                        }
                    }
                }
                // Swap low and high bytes
                crc =((crc &0xFF)<<8)|((crc >> 8)& 0xFF);
                return crc.tostring(16).toUpperCase().padstart(4,'0');
            }






            //if(index= 1){
            //    if(numPointsValue = 0){
            //       //发送 FF100020001C38 0001 00320032003200320032 00320032003200320032 00320032003200320032 00320032003200320032  00320032003200320032 001FFFFF 1C8F 
            //       //                    频率 占空比
            //    };
            //};












            //初始化权重值列表
            function clearPointsList() {
                var pointsList = document.getElementById("pointsList");
                while (pointsList.firstChild) {
                    pointsList.removeChild(pointsList.firstChild);
                }
            }

            console.log("2222222222222" + x_ac);
            var headingDu;
            if (parseFloat(vel_G) > 1) {
                headingDu = heading;
                console.log("wdbubibiubiububiu");
            } else {
                headingDu = x_ac;
                console.log("wewweweweewewewewe");
            };
            // ----调用函数，更新线段----
            updatePointsAndLine(headingDu);
            //----- 更新导航数据 -------
            updateNavigationData();
        }
    }
}
//------显示经纬度等数据-----------
function updateNavigationData() {
    if (latitude != null && longitude != null) {
        document.getElementById('latitude').textContent = latitude.toFixed(6);
        document.getElementById('longitude').textContent = longitude.toFixed(6);
        document.getElementById('heading').textContent = heading.toFixed(2);
        document.getElementById('vel_G').textContent = vel_G.toFixed(2);
        document.getElementById('north_Distance').textContent = north_Distance.toFixed(2);
        document.getElementById('east_Distance').textContent = east_Distance.toFixed(2);
    }
}
setInterval(processData, 2000);

//-------导航按键判断--------
document.getElementById('switch_G').addEventListener('change', function () {
    isLocationEnabled = this.checked; // this.checked 为 true 或 false
    if (isLocationEnabled) {
        console.log("位置检索已启用");
    } else {
        console.log("位置检索已禁用");
    }
});

//-------航线按键判断--------
document.getElementById('curveSwitch').addEventListener('change', function () {
    isCurveEnabled = this.checked; // this.checked 为 true 或 false
    if (isCurveEnabled) {
        console.log("Curve显示已启用");
    } else {
        console.log("Curve显示已禁用");
    }
});
//-------路径加载--------
document.getElementById('updateFileListButton').addEventListener('click', function () {
    updateFileList();
});

//-------------放入全局变量当中----------------------
var selectedFileName = null; // 用于存储选中的文件名

function updateFileList() {
    var fileListHtml = "";
    var files = JSON.parse(android.getFileListFromDownload()); // 从 Android 端获取文件列表
    files.forEach(function (file) {
        fileListHtml += "<li onclick='selectFile(\"" + file + "\")'>" + file + "</li>";
    });
    document.getElementById("fileList").innerHTML = fileListHtml;
}
function selectFile(fileName) {
    selectedFileName = fileName;
    console.log("Selected file: " + selectedFileName);
    // 可以在这里添加额外的逻辑，比如高亮显示选中的文件项
}

//-------------放入全局变量当中----------------------
var curves; // 声明在全局作用域

function loadFile(fileName) {
    var fileContent = android.loadFileToMap(fileName); // 从 Android 端加载文件内容
    if (fileContent) {
        var convertedData = JSON.parse(fileContent);
        var latlngs = convertedData.map(entry => [entry.lat, entry.lng]);

        console.log(latlngs);
        if (curves) {
            map.removeLayer(curves); // 如果curves已存在，先移除旧的图层
        }
        curves = L.polyline(latlngs, { color: 'red' }).addTo(map);
    } else {
        alert('无法加载文件: ' + fileName);
    }
}

document.getElementById('loadFileToMapButton').addEventListener('click', function () {
    if (selectedFileName) {
        loadFile(selectedFileName);
    } else {
        alert('请先选择一个路径文件！');
    }
});

// -----------------------------处方图文件输入--------------------------------
document.getElementById('geojsonFileInput').addEventListener('change', function (event) {
    console.log("111111111");
    var fileReader = new FileReader();
    fileReader.onload = function (e) {
        var geojsonData = JSON.parse(e.target.result);
        processedGeojsonData = geojsonData;
        console.log("Processed GeoJSON:", processedGeojsonData);

        //      L.geoJSON(processedGeojsonData, {
        //          onEachFeature: function (feature, layer) {
        //              // 针对每个特征的逻辑
        //          }
        //      }).addTo(map);

        L.geoJSON(geojsonData, {
            style: function (feature) {
                let fillColor;
                switch (feature.properties.NUMPOINTS) {
                    case 11.0:
                        fillColor = "#d7191c"; // 红色填充
                        break;
                    case 10.0:
                        fillColor = "#e54f35";
                        break;
                    case 9.0:
                        fillColor = "#f3854e";
                        break;
                    case 8.0:
                        fillColor = "#fdb56a";
                        break;
                    case 7.0:
                        fillColor = "#fed38c";
                        break;
                    case 6.0:
                        fillColor = "#fff0af";
                        break;
                    case 5.0:
                        fillColor = "#eff8b0"; // 红色填充
                        break;
                    case 4.0:
                        fillColor = "#ceea91"; // 红色填充
                        break;
                    case 3.0:
                        fillColor = "#aedc72"; // 红色填充
                        break;
                    case 2.0:
                        fillColor = "#80c75f"; // 红色填充
                        break;
                    case 1.0:
                        fillColor = "#4dae50"; // 红色填充
                        break;
                    case 0.0:
                        fillColor = "#1a9641"; // 蓝色填充
                        break;
                    default:
                        fillColor = "#ffffff"; // 默认白色填充
                }
                return {
                    color: "#ffffff",      // 边框颜色
                    weight: 0.5,
                    fillColor: fillColor,  // 填充颜色
                    fillOpacity: 1       // 填充不透明度
                };
            }
        }).addTo(map);
    };
    fileReader.onerror = function () {
        console.error('Error reading the GeoJSON file');
    };
    fileReader.readAsText(event.target.files[0]);
});




//------------------------列表选择处方图文件-------------------
document.getElementById('updateGeojsonListButton').addEventListener('click', function () {
    updateGeojsonList();
});

var selectedGeojsonFileName = null; // 用于存储选中的 Geojson 文件名

function updateGeojsonList() {
    var geojsonListHtml = "";
    var geojsonFiles = JSON.parse(android.getFileListFromGeojson()); // 从 Android 端获取 Geojson 文件列表
    geojsonFiles.forEach(function (geojsonFile) {
        geojsonListHtml += "<li onclick='selectGeojsonFile(\"" + geojsonFile + "\")'>" + geojsonFile + "</li>";
    });
    document.getElementById("geojsonList").innerHTML = geojsonListHtml;
}

function selectGeojsonFile(geojsonFileName) {
    selectedGeojsonFileName = geojsonFileName;
    console.log("Selected Geojson file: " + selectedGeojsonFileName);
    // 可以在这里添加额外的逻辑，比如高亮显示选中的 Geojson 文件项
}

//-------------放入全局变量当中----------------------
var geojsonLayer; // 声明在全局作用域

function loadGeojsonFile(geojsonFileName) {
    var geojsonContent = android.loadGeojsonFile(geojsonFileName); // 从 Android 端加载 Geojson 文件内容
    if (geojsonContent) {
        var geojsonData = JSON.parse(geojsonContent);

        if (geojsonLayer) {
            map.removeLayer(geojsonLayer); // 如果 geojsonLayer 已存在，先移除旧的图层
        }

        L.geoJSON(geojsonData, {
            style: function (feature) {
                let fillColor;
                switch (feature.properties.NUMPOINTS) {
                    case 11.0:
                        fillColor = "#d7191c"; // 红色填充
                        break;
                    case 10.0:
                        fillColor = "#e54f35";
                        break;
                    case 9.0:
                        fillColor = "#f3854e";
                        break;
                    case 8.0:
                        fillColor = "#fdb56a";
                        break;
                    case 7.0:
                        fillColor = "#fed38c";
                        break;
                    case 6.0:
                        fillColor = "#fff0af";
                        break;
                    case 5.0:
                        fillColor = "#eff8b0"; // 红色填充
                        break;
                    case 4.0:
                        fillColor = "#ceea91"; // 红色填充
                        break;
                    case 3.0:
                        fillColor = "#aedc72"; // 红色填充
                        break;
                    case 2.0:
                        fillColor = "#80c75f"; // 红色填充
                        break;
                    case 1.0:
                        fillColor = "#4dae50"; // 红色填充
                        break;
                    case 0.0:
                        fillColor = "#1a9641"; // 蓝色填充
                        break;
                    default:
                        fillColor = "#ffffff"; // 默认白色填充
                }
                return {
                    color: "#ffffff",      // 边框颜色
                    weight: 0.5,
                    fillColor: fillColor,  // 填充颜色
                    fillOpacity: 1       // 填充不透明度
                };
            }
        }).addTo(map);

        // 可以在这里添加额外的逻辑，比如缩放地图以适应加载的 Geojson 数据
        map.fitBounds(geojsonLayer.getBounds());
    } else {
        alert('无法加载 Geojson 文件: ' + geojsonFileName);
    }
}

document.getElementById('loadGeojsonFileToMapButton').addEventListener('click', function () {
    if (selectedGeojsonFileName) {
        loadGeojsonFile(selectedGeojsonFileName);
    } else {
        alert('请先选择一个 Geojson 文件！');
    }
});


// ----获取司南导航定位按钮元素放大到当前位置----
const locateButton = document.getElementById('locate-btn');
// 定位按钮点击事件
locateButton.addEventListener('click', function () {
    // 移动地图视图到自定义的经纬度并放大
    map.setView([latitude, longitude], 18)


    //---------解析到当前位置---------
    // 使用Mapbox Geocoding API进行地理编码
    var geocodingUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?access_token=pk.eyJ1IjoiZWdnMzY1IiwiYSI6ImNscTdvN3B3bDB0eXIya3A3NWhoYnJhd2gifQ.-JKqIgzJlA8gZ7cZ4i8u2A`;

    // 发起API请求
    fetch(geocodingUrl)
        .then(response => response.json())
        .then(data => {
            // 在此处理响应的位置数据
            if (data.features && data.features.length > 0) {
                // 取得第一个地点的名称
                var placeName = data.features[0].place_name;
                document.getElementById('on_place').textContent = placeName;
                // 输出地点名称或进行其他处理
                console.log(placeName);
            } else {
                console.log("No results found");
            }
        });

});


// Three.js 初始化
function initThreeJS() {
    // 创建场景
    const scene = new THREE.Scene();

    // 创建相机
    const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000); // 使用1:1的宽高比
    camera.position.set(30, 0, 30);

    // 创建渲染器并添加到HTML
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(200, 200); // 调整渲染器大小
    renderer.setClearColor(0xffffff); // 设置背景颜色为白色
    document.getElementById("content_fourshu").appendChild(renderer.domElement);

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040); // soft white light
    scene.add(ambientLight);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    scene.add(directionalLight);

    // 主体
    var bodyGeometry = new THREE.BoxGeometry(3, 1, 2);
    var bodyMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
    var body = new THREE.Mesh(bodyGeometry, bodyMaterial);

    // 车顶
    var cabinGeometry = new THREE.BoxGeometry(1, 0.5, 1.5);
    var cabinMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
    var cabin = new THREE.Mesh(cabinGeometry, cabinMaterial);
    cabin.position.set(0, 0.75, 0);

    // 车轮
    var wheelGeometry = new THREE.CylinderGeometry(0.5, 0.5, 1, 32);
    var wheelMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    var wheelPositions = [
        { x: -1.5, y: -0.5, z: 1 },
        { x: -1.5, y: -0.5, z: -1 },
        { x: 1.5, y: -0.5, z: 1 },
        { x: 1.5, y: -0.5, z: -1 }
    ];

    var wheels = wheelPositions.map(function (pos) {
        var wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
        wheel.rotation.x = Math.PI / 2; // Rotate the wheel 90 degrees
        wheel.position.set(pos.x, pos.y, pos.z);
        return wheel;
    });

    // 组装拖拉机
    var tractor = new THREE.Group();
    tractor.add(body);
    tractor.add(cabin);
    wheels.forEach(function (wheel) {
        tractor.add(wheel);
    });

    // 将拖拉机置于地面之上
    tractor.position.y = 0.5;
    tractor.scale.set(9, 9, 9); // 调整模型尺寸

    // 添加到场景
    scene.add(tractor);

    // 创建喷杆的几何体和材料
    var sprayBarGeometry = new THREE.BoxGeometry(0.2, 0.2, 5); // 宽、高、长
    var sprayBarMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
    var sprayBar = new THREE.Mesh(sprayBarGeometry, sprayBarMaterial);

    // 定位喷杆在拖拉机前方
    sprayBar.position.set(2, 0.5, 0); // 调整位置以匹配拖拉机的前端

    // 将喷杆添加到拖拉机上
    tractor.add(sprayBar);

    // 创建OrbitControls
    const controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.target = tractor.position; // 设置控制的目标为拖拉机位置
    controls.update(); // 必须在设置了target之后调用

    // // 定义一个四元数表示喷杆的旋转
    // var sprayBarQuaternion = new THREE.Quaternion();

    // sprayBarQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 18); // 以Y轴为轴，旋转10度

    // // 动画循环
    // function animate() {
    //     requestAnimationFrame(animate);
    //     // 应用四元数旋转到喷杆
    //     sprayBar.quaternion.multiplyQuaternions(sprayBar.quaternion, sprayBarQuaternion);

    //     //    // 更新控制器
    //     controls.update();
    //     renderer.render(scene, camera);
    // }

    // animate(); // 启动动画循环

    console.log("wwswwwwwwwwww" + x_qua);
    // 动画循环
    function animate() {
        requestAnimationFrame(animate);

        // 创建一个新的四元数用于存储喷杆的旋转状态
        var sprayBarRotation = new THREE.Quaternion();

        // 将从传感器返回的四元数值应用到喷杆的旋转状态中
        sprayBarRotation.multiplyQuaternions(x_qua, y_qua);
        sprayBarRotation.multiply(z_qua);

        // 应用四元数旋转到喷杆
        sprayBar.quaternion.copy(sprayBarRotation);

        // 更新控制器
        controls.update();
        renderer.render(scene, camera);
    }

    animate(); // 启动动画循环

}

// 停止动画循环
function stopAnimation() {
    // 如果有需要，在这里停止动画循环
}
